// 获取可以预定的时间段
const getFreeTimeSlot = (order, timeSlots) => {
    for (let timeSlot of timeSlots) {
        if (timeSlot.startTime >= order.startTime && timeSlot.endTime <= order.endTime) {
            timeSlot.notFree = true;
        }
    }
};

const formatTime = (milliseconds) => {
    const date = new Date(milliseconds);
    const hours = date.getHours();
    const minutes = date.getMinutes();

    const formattedHours = hours < 10 ? `0${hours}` : hours;
    const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;

    return `${formattedHours}:${formattedMinutes}`;
};

const handler = (sales, date, venue, orders) => {
    let results = [];
    // // 获取场地开放的时间范围
    // let timeSlot = getTimeSlot(venue.venueTimeSlotResponses);
    // 场地支持预定的时间段
    let timeSlotList = venue.venueTimeSlotResponses;
    // 获取场地列表
    let venueList = venue.venueResponses;
    // 需要监控的场地与时间段
    let monitorVenues = sales.venues;
    if (!monitorVenues || monitorVenues.length <= 0) {
        return;
    }
    // 遍历场地列表 同时比对订单列表 找出已经被预定的场地时间
    for (let venue of venueList) {
        // 当前场地已经被预定的时间
        let orderList = orders.filter(it => it.venueId === venue.venueId);
        let timeSlots = JSON.parse(JSON.stringify(timeSlotList));
        for (let order of orderList) {
            getFreeTimeSlot(order, timeSlots);
        }
        let tss = timeSlots.filter(it => !it.notFree);
        if (tss.length > 0) {
            // TODO 判断监控的场地列表是否有可预定的
            const ts = tss.map(obj => `${formatTime(obj.startTime)}-${formatTime(obj.endTime)}`);
            const result = `${sales.name} ${date.dayName} 有空场地 ${venue.venueName} [ ${ts.join(', ')} ]`;
            results.push(result);
        } else {
            // console.error(`${date.dayName} ${venue.venueName} 没有场地`);
        }
    }
    console.log(results.join('\n'));
};

module.exports = handler;